<?php
//命名空间
    namespace Admin\Controller;
    use Think\Controller;

    class WechatController extends Controller{
        private $fromUsername;
        private $toUsername;
        private $time;

        //判断验证还是回复
        public function judgeType(){
            if(empty(I('echostr'))){
                $this->main();
            }else{
                $this->valid();
            }
        }

        /**
         * 主函数
         * @return void
         */
        private function main(){

            $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
            if (!empty($postStr)){
                libxml_disable_entity_loader(true);
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                //分配属性
                $this->fromUsername = $postObj->FromUserName;
                $this->toUsername = $postObj->ToUserName;
                $this->time = time();

                $msgType = $postObj->MsgType;
                /*判断消息类型*/
                switch ($msgType) {
                    /*****文本消息*****/
                    case 'text':
                        //接收关键字
                        $keyword = trim($postObj->Content);
                        $this->judgeText($keyword);
                        break;
                    /*****事件*****/
                    case 'event':
                        $event = $postObj->Event; //事件类型
                        $this->judgeEvent($event,$postObj);
                        break;
                }

            }else {
                echo "";
                exit;
            }
        }

        /**
         * 判断关键字
         * @param string $keyword 关键字
         * @return void
         */
        private function judgeText($keyword){
            $data = M('reply')->where(array('keyword'=>$keyword))->find();
            if(empty($data)){
                echo '';
            }
            switch($data['type']){
                case '1':
                    $this->responseMsg($data['content']);
                    break;
                case '2':
                    $title = array($data['content']);
                    $img = array('http://120.27.122.236/Public/'.$data['img']);
                    $link = array('http://www.baidu.com');
                    $this->judgeNews($title,$title,$img,$link);
                    break;
            }
        }

        /**
         * 判断图文消息，注意四个数组的值个数要相同
         * @param array $title 标题
         * @param array $description 描述
         * @param array $img 图片路径
         * @param array $link 跳转链接
         * @return void
         */
        private function judgeNews($title,$description,$img,$link){
            $count = count($title);
            $item = '';
            for($i = 0; $i < $count; $i++){
                $item .= '<item><Title><![CDATA['.$title[$i].']]></Title>';
                $item .= '<Description><![CDATA['.$description[$i].']]></Description>';
                $item .= '<PicUrl><![CDATA['.$img[$i].']]></PicUrl>';
                $item .= '<Url><![CDATA['.$link[$i].']]></Url></item>';
            }
            $this->responseNews($count,$item);
        }

        /**
         * 判断事件
         * @param string $event 事件类型
         * @param object $postObj xml对象
         * @return void
         */
        private function judgeEvent($event,$postObj){
            switch ($event) {
                case 'CLICK':
                    $key = $postObj->EventKey;
                    $this->judgeEventKey($key);
                    break;
            }
        }

        /**
         * 判断点击事件
         * @param string $key 事件的key
         * @return void
         */
        private function judgeEventKey($key){
            $data = M('reply')->where(array('keyword'=>$key))->find();
            if(empty($data)){
                echo '';
            }
            $this->responseMsg($data['content']);
        }

        /**
         * 回复文本消息
         * @param string $contentStr 输出内容
         * @return void
         */
        private function responseMsg($contentStr){
            $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[text]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        </xml>";
            $resultStr = sprintf($textTpl, $this->fromUsername, $this->toUsername, $this->time, $contentStr);
            echo $resultStr;
        }

        /**
         * 回复图文消息
         * @param int $count 图文消息的个数
         * @param int $item 图文消息的主体内容
         * @return void
         */
        private function responseNews($count,$item){
            $newsTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[news]]></MsgType>
                        <ArticleCount>%s</ArticleCount>
                        <Articles>
                            %s
                        </Articles>
                        </xml> ";
            $resultStr = sprintf($newsTpl, $this->fromUsername, $this->toUsername, $this->time, $count, $item);
            echo $resultStr;
        }

        //验证token
        private function valid()
        {
            $echoStr = $_GET["echostr"];

            //valid signature , option
            if($this->checkSignature()){
                echo $echoStr;
                exit;
            }
        }

        //检查检名
        private function checkSignature()
        {
            $base = M('base')->field('token')->find();
            // you must define TOKEN by yourself
            if (empty($base['token'])) {
                throw new Exception('TOKEN is not defined!');
            }

            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];

            $token = $base['token'];
            $tmpArr = array($token, $timestamp, $nonce);
            // use SORT_STRING rule
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode( $tmpArr );
            $tmpStr = sha1( $tmpStr );

            if( $tmpStr == $signature ){
                return true;
            }else{
                return false;
            }
        }

    }


?>